package com.grass.cropTradingCenter.utils;

import com.grass.cropTradingCenter.common.BusinessException;
import com.grass.cropTradingCenter.common.LoginInfo;
import com.grass.cropTradingCenter.common.ResultCode;

public class SecurityUtils {

    private static ThreadLocal<LoginInfo> USER_THREAD_LOCAL = new ThreadLocal<>();


    /**
     * 设置当前用户
     * @param
     */
    public static void setLoginUser(LoginInfo info){
        USER_THREAD_LOCAL.set(info);
    }

    /**
     * 清除当前登录用户
     */
    public static void clearLoginUser() {
        USER_THREAD_LOCAL.remove();
    }

    /**
     * 获取当前登录用户
     * @return
     */

    public static int getUserId() {
        LoginInfo info = USER_THREAD_LOCAL.get();
        if (null == info.getUserId() || info.getUserId() == 0) {
            throw new BusinessException(ResultCode.NO_LOGIN);
        }
        if(!"user".equals(info.getType())) throw new BusinessException(ResultCode.NO_LOGIN);
        return info.getUserId();
    }

    public static int getShopUserId() {
        LoginInfo info = USER_THREAD_LOCAL.get();
        if (null == info.getUserId() || info.getUserId() == 0) {
            throw new BusinessException(ResultCode.NO_LOGIN);
        }
        if(!"shop".equals(info.getType())) throw new BusinessException(ResultCode.NO_LOGIN);
        return info.getUserId();
    }

    public static int getAdminUserId() {
        LoginInfo info = USER_THREAD_LOCAL.get();
        if (null == info.getUserId() || info.getUserId() == 0) {
            throw new BusinessException(ResultCode.NO_LOGIN);
        }
        if(!"admin".equals(info.getType())) throw new BusinessException(ResultCode.NO_LOGIN);
        return info.getUserId();
    }
}
